// import { DownOutlined, PlusOutlined } from '@ant-design/icons';
import AuthComponent from '@/components/Authorized/AuthComponent';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import {
  Button,
  message,
  DatePicker,
  Radio,
  Input,
  Select,
} from 'antd';
import React, { useState, useCallback, useRef, useEffect } from 'react';
import ProTable from '@ant-design/pro-table';
import { useRequest } from '@umijs/hooks';
import { counterUpgradPage, counterUpgraddetailExcel, queryCityInfo } from './service';
import moment from 'moment';
import styles from './index.less';
const { Option } = Select;

// let hiddenData = null;
const TableList = (props) => {
  const { data: selectData } = useRequest(queryCityInfo);
  const [createModalVisible, handleModalVisible] = useState(false);
  const [exportFlag, handleExportFlag] = useState('')
  const actionRef = useRef();
  const ref = useRef();
  const searchRef = useRef();
  const reloadTable = useCallback(function reloadData() {
    if (searchRef.current) {
      searchRef.current.click();
    }
  }, []);

  const [height, controlH] = useState(300);

  const [isCollapse, controlC] = useState(true);
  useEffect(() => {
    if (isCollapse) {
      controlH(document.body.clientHeight - 380);
    } else {
      controlH(document.body.clientHeight - 470);
    }
  }, [isCollapse])
    const formatFlightNo = (val) => {
      if (!val) {
        return '';
      } else if (val.length < 3 || /^\D/.test(val)) {
        return ''.toUpperCase.call(val);
      } else if (/^\d{2}/.test(val)) {
        return `3U${val}`;
      } else {
        return val;
      }
    }
  const columns = [
    {
      title: '航班号',
      dataIndex: 'flightNo',
      width: 80,
      renderFormItem: (_, { type, defaultRender, ...rest }) => {
        return <Input
          {...rest}
          onChange= {e => {
            e.target.value = formatFlightNo(e.target.value);
            rest.onChange(e.target.value)
          }}
          allowClear maxLength={6} placeholder="3U" />;
      }
    },
    {
      title: '航班开始日期',
      hideInTable: true,
      dataIndex: 'flightStartDate',
      renderFormItem: (_, { ...rest }) => {
        const format = 'YYYY-MM-DD';
        return (
          <DatePicker
            style={{width: '80%'}}
            format={format}
            {...rest}
          />
        );
      },
    },
    {
      title: '航班结束日期',
      hideInTable: true,
      dataIndex: 'flightEndDate',
      renderFormItem: (_, { ...rest }) => {
        const format = 'YYYY-MM-DD';
        return (
          <DatePicker
            style={{width: '80%'}}
            format={format}
            {...rest}
          />
        );
      },
    },
    {
      // 多个查询选项
      title: '出发地',
      dataIndex: 'org',
      width: 80,
      // hideInTable: true,
      initialValue: '', //缺个默认接口服务航站
      renderFormItem: (_, { ...rest }, form) => {
        return (
          <Select
            allowClear={true}
            showSearch
            placeholder="请选择"
            defaultActiveFirstOption={false}
            showArrow={false}
            filterOption={true}
            optionFilterProp="children"
            notFoundContent={null}
            {...rest}
          >
            {selectData &&
              selectData.map((v, i) => {
                return (
                  <Option key={v.CITY3CODE}>{v.CITYNAME}-{v.CITY3CODE}</Option>
                )
              })
            }
          </Select>
        );
      },
    },
    {
      // 多个查询选项
      title: '目的地',
      dataIndex: 'dst',
      width: 80,
      // hideInTable: true,
      initialValue: '', //缺个默认接口服务航站
      renderFormItem: (_, { ...rest }, form) => {
        return (
          <Select
            allowClear={true}
            showSearch
            placeholder="请选择"
            defaultActiveFirstOption={false}
            showArrow={false}
            filterOption={true}
            optionFilterProp="children"
            notFoundContent={null}
            {...rest}
          >
            {selectData &&
              selectData.map((v, i) => {
                return (
                  <Option key={v.CITY3CODE}>{v.CITYNAME}-{v.CITY3CODE}</Option>
                )
              })
            }
          </Select>
        );
      },
    },
    {
      title: '主批号码',
      dataIndex: 'batchGroupNumber',
      hideInSearch: true,
      width: 80,
    },
    {
      title: '子批号码',
      dataIndex: 'subBatchNumber',
      hideInSearch: true,
      width: 80,
    },
    {
      title: '代理号',
      dataIndex: 'agentNumber',
      hideInSearch: true,
      width: 80,
    },
    {
      // title: '纸质',
      title: '纸质单类型',
      dataIndex: 'paper',
      hideInSearch: true,
      width: 90,
    },
    {
      // title: '单类型',
      title: '单号',
      dataIndex: 'ticketType',
      width: 60,
    },
    {
      title: '纸质单检查',
      hideInSearch: true,
      dataIndex: 'paperCheck',
      width: 100,
    },
    {
      title: '出票日期',
      hideInSearch: true,
      dataIndex: 'tktIssueDate',
      width: 80,
    },
    {
      title: '旅客类型',
      hideInSearch: true,
      dataIndex: 'passengerType',
      width: 80,
    },
    {
      title: '补差/变更标识',
      hideInSearch: true,
      dataIndex: 'changeSign',
      width: 120,
    },
    {
      title: '关联公司',
      dataIndex: 'connectedCompany',
      width: 80,
    },
    {
      title: '关联类型',
      hideInSearch: true,
      dataIndex: 'connectedType',
      width: 80,
    },
    {
      title: '关联票号',
      hideInSearch: true,
      dataIndex: 'connectedTktNo',
      width: 80,
    },
    {
      title: '关联票联号',
      hideInSearch: true,
      dataIndex: 'tktCNo',
      width: 90,
    },
    {
      title: '票面金额',
      hideInSearch: true,
      dataIndex: 'denomination',
      width: 80,
    },
    {
      title: '库存检查',
      hideInSearch: true,
      dataIndex: 'inventoryCheck',
      width: 80,
    },
    {
      title: '飞行日期',
      hideInSearch: true,
      dataIndex: 'flightDate',
      width: 80,
    },
    {
      title: '承运人',
      hideInSearch: true,
      dataIndex: 'carrier',
      width: 80,
    },
    {
      title: '舱位',
      hideInSearch: true,
      dataIndex: 'cabin',
      width: 60,
    },{
      title: '运价基础',
      hideInSearch: true,
      dataIndex: 'fareBasis',
      width: 80,
    },
    {
      title: '旅游编号',
      hideInSearch: true,
      dataIndex: 'travelNo',
      width: 80,
    }
  ];
  const [inited, setInited] = useState(false);
  const [firstLoadDate, setFirstLoadDate] = useState(true);
  // const [orderSaleDate, setorderSaleDate] = useState(true)
  useEffect(() => {
    if (actionRef.current && inited) {
       reloadTable();
    } else {
      setInited(true);
    }
  }, [inited]);

    // 切换清空搜索
  //   useEffect(() => {
  //     hiddenData = null
  //   // eslint-disable-next-line react-hooks/exhaustive-deps
  //   }, [])
  // 获取列表详情方法
  const beforeSearchSubmit = useCallback(params => {
    params['flightStartDate'] = params.flightStartDate ? params.flightStartDate.format('YYYY-MM-DD') : '';
    params['flightEndDate'] = params.flightEndDate ? params.flightEndDate.format('YYYY-MM-DD') : '';
    if (!isCollapse) {
      return { ...params }
    } else {
      if (event&&event.target&&event.target.querySelector&&event.target.querySelector('span') && event.target.querySelector('span').innerText === '查 询') {
        if (Object.keys(params).indexOf('flightStartDate') === -1) {
          params.flightStartDate = ''
        }
        if (Object.keys(params).indexOf('flightEndDate') === -1) {
          params.flightEndDate = ''
        }
      } else if (event&&event.target&&event.target.querySelector&&event.target.querySelector('span') && event.target.querySelector('span').innerText === '重 置') {
        ref.current.setFieldsValue({
          flightStartDate: moment(),
          flightEndDate: moment() ,
        })
        // hiddenData = {}
      }
      // return { ...hiddenData, ...params }
      return { ...params }
    }
  }, []);
  const [selectedRowKeys, handleSelectedRowKeys] = useState([]) // 勾选索引
  const [selectedRows, handleSelectedRows] = useState([]) // 勾选列
  const [searchParams, handleSearchParams] = useState() // 存储搜索条件
  // 选中添加值
  const tableSelectChange = (selectedRowKeys, selectedRows) => {
    handleSelectedRowKeys(selectedRowKeys);
    handleSelectedRows(selectedRows);
  };
  // 设置选中的值
  const rowSelection = {
    selectedRowKeys,
    onChange: tableSelectChange,
  };
  //导出方法
  const handleExport = () => {
    if (!exportFlag){
      message.error('表格数据为空')
      return false
    }
    const hide = message.loading('正在导出');
    let res = counterUpgraddetailExcel(searchParams)
      .then(res => {
        let blob = new Blob([res], {
          type:
            'application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        });
        let elink = document.createElement('a');
        let time=moment(Date.now()).format('YYYY-MM-DD HH_ss_mm')
        elink.download = '柜台升舱录入模板'+time+'.xls'
        elink.style.display = 'none';
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click();
        document.body.removeChild(elink);
        hide();
        message.success('导出成功');
      })
      .catch(err => {
        console.log(err);
      });
  };

  return (
    <>
      <ProTable
        options={{density: false,fullScreen:true, reload:false, setting:true}}
        actionRef={actionRef}
        formRef={ref}
        dateFormatter="YYYY-MM-DD"
        scroll={{ x: 180, y: height }}
        size='small'
        className={`${styles.viproomsaleCharts} rest-pro-table-form-compact ${isCollapse?'':'collapse'}`}
        search={{
          searchText: (
            <span ref={searchRef} href>
              查询
            </span>
          ),
          onCollapse: val => {
            controlC(val)
            // if (!val && hiddenData) {
            //   ref.current.setFieldsValue({
            //     flightNo:hiddenData.flightNo,
            //     // flightStartDate: hiddenData.flightStartDate,
            //     // flightEndDate: hiddenData.flightEndDate,
            //     org: hiddenData.org,
            //     dst:hiddenData.dst,
            //     ticketType: hiddenData.ticketType,
            //     connectedCompany: hiddenData.connectedCompany,
            //   })
            // } else {
            //   hiddenData = ref.current.getFieldsValue()
            // }
          },
          span: { //设置排列方式
            xs: 24,
            sm: 24,
            md: 6,
            lg: 6,
            xl: 6,
            xxl: 6,
          }
        }}
        toolBarRender={() => [
           <AuthComponent authCode="mkt.countupgradeimportDemo.export">
           <Button icon="download" type="primary" onClick={handleExport} selectedKeys={[]} style={{ padding: '0px 0px 0px 8px',width:'73px' }}>
            导出           
          </Button>
          </AuthComponent>
        ]}
        headerTitle={
          <div>
            <span style={{ paddingRight: 10, fontWeight: "bold", color: "#000" }}>柜台升舱录入模板</span>
          </div>
        }
        beforeSearchSubmit={beforeSearchSubmit}
        request={params => {
          if (!params['flightStartDate'] && !params['endState']&& firstLoadDate) {
            setFirstLoadDate(false)
            params['flightStartDate'] = moment().format('YYYY-MM-DD');
            params['flightEndDate'] = moment().format('YYYY-MM-DD');
            ref.current.setFieldsValue({
              flightStartDate: moment()
            })
            ref.current.setFieldsValue({
              flightEndDate: moment()
            })
          }
          // if (!params['org']) {
          //   ref.current.setFieldsValue({
          //     org: ''
          //   })
          // }
          if (!params['flightNo']) {
            ref.current.setFieldsValue({
              flightNo: ''
            })
          }
          // if (!params['dst']) {
          //   ref.current.setFieldsValue({
          //     dst: ''
          //   })
          // }
          if (!params['connectedCompany']) {
            ref.current.setFieldsValue({
              connectedCompany: ''
            })
          }
          if (!params['ticketType']) {
            ref.current.setFieldsValue({
              ticketType: ''
            })
          }
          handleSearchParams(params);
          return counterUpgradPage(params);
        }}
        postData={data => {
          if (data.length === 0) {
            handleExportFlag(false)
          } else {
            handleExportFlag(true)
          }
          return data
        }}
        onRow={record => {
          return {
            onClick: () => {
            },
          };
        }}
        columns={columns}
        rowKey="id"
        pagination={{
          showSizeChanger: true,
          showTotal: (total, range) => `${range[0]}-${range[1]} 共 ${total} 项`
        }}
      />
    </>
  );
};

export default Form.create()(TableList);
